package com.xxxx.rpc.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Objects;

/**
 * @Desc
 * @Author lsh
 * @Create Time 2021/1/4 12:42
 */
@Configuration
public class EsConfig {
    @Value("${elasticsearch.address}")
    private  String[]address;
    private final static String SCHEME="HTTP";

    @Bean
    public HttpHost builderHttpHost(String s){
        String[] address = s.split(":");
        if (2!=address.length){
            return null;
        }
        String host = address[0];
        Integer port = Integer.valueOf(address[1]);
        return new HttpHost(host,port,SCHEME);
    }
    @Bean
    public RestClientBuilder restClientBuilder(){
       HttpHost[]hosts = Arrays.stream(address)
               .map(this::builderHttpHost)
               .filter(Objects::nonNull)
               .toArray(HttpHost[]::new);
       return RestClient.builder(hosts);
    }
    @Bean
    public RestHighLevelClient restHighLevelClient(@Autowired RestClientBuilder restClientBuilder){
        return new RestHighLevelClient(restClientBuilder);
    }
}
